#include "../include/head.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 全局商品链表
ListNode *goods_list = NULL;

// 商品比较函数（按ID）
int compare_goods_by_id(void *a, void *b) {
    Goods *goods_a = (Goods*)a;
    char *id_b = (char*)b;
    return strcmp(goods_a->id, id_b) == 0 ? 0 : 1;
}

// 商品比较函数（按名称）
int compare_goods_by_name(void *a, void *b) {
    Goods *goods_a = (Goods*)a;
    char *name_b = (char*)b;
    return strcmp(goods_a->name, name_b) == 0 ? 0 : 1;
}

// 从文件加载所有商品到链表
void load_all_goods() {
    FILE *file = fopen("./supermarket_management/data/goods.txt", "r");
    if (file) {
        Goods *goods;
        while (1) {
            goods = (Goods*)malloc(sizeof(Goods));
            if (fscanf(file, "%19[^,],%99[^,],%lf,%d,%49[^,],%d\n",
                    goods->id,
                    goods->name,
                    &goods->price,
                    &goods->stock,
                    goods->category,
                    &goods->is_special) != 6) {
                free(goods);
                break;
            }
            insert_at_end(&goods_list, goods);
        }
        fclose(file);
        printf("已加载 %d 个商品到内存\n", get_list_length(goods_list));
    } else {
        printf("商品文件不存在，将创建新的商品数据\n");
    }
}

// 保存所有商品到文件
void save_all_goods() {
    FILE *file = fopen("./supermarket_management/data/goods.txt", "w");
    if (file) {
        ListNode *current = goods_list;
        while (current != NULL) {
            Goods *goods = (Goods*)current->data;
            fprintf(file, "%s,%s,%.2f,%d,%s,%d\n",
                    goods->id,
                    goods->name,
                    goods->price,
                    goods->stock,
                    goods->category,
                    goods->is_special);
            current = current->next;
        }
        fclose(file);
        printf("所有商品数据已保存\n");
    } else {
        printf("保存商品数据失败\n");
    }
}

// 添加商品
Goods* add_goods() {
    Goods *new_goods = (Goods*)malloc(sizeof(Goods));
    if (new_goods == NULL) {
        printf("内存分配失败\n");
        return NULL;
    }
    
    printf("\n========== 添加商品 ==========\n");
    
    // 输入商品ID并检查重复
    while (1) {
        printf("请输入商品ID（t-特价, v-蔬菜, f-水果等）: ");
        scanf("%s", new_goods->id);
        
        if (find_node(goods_list, new_goods->id, compare_goods_by_id) != NULL) {
            printf("商品ID已存在，请重新输入\n");
        } else {
            break;
        }
    }
    
    printf("请输入商品名称: ");
    scanf("%s", new_goods->name);
    
    printf("请输入商品价格: ");
    scanf("%lf", &new_goods->price);
    
    printf("请输入商品库存: ");
    scanf("%d", &new_goods->stock);
    
    printf("请输入商品分类: ");
    scanf("%s", new_goods->category);
    
    printf("是否是特价商品（0-否，1-是）: ");
    scanf("%d", &new_goods->is_special);
    
    // 添加到商品链表
    insert_at_end(&goods_list, new_goods);
    
    // 保存商品数据到文件
    save_all_goods();
    
    printf("商品添加成功！\n");
    show_goods(new_goods);
    
    return new_goods;
}

// 显示商品信息
void show_goods(Goods *goods) {
    if (goods == NULL) {
        printf("错误：商品信息为空\n");
        return;
    }
    
    printf("\n========== 商品信息 ==========\n");
    printf("商品ID: %s\n", goods->id);
    printf("商品名称: %s\n", goods->name);
    printf("商品价格: %.2f元\n", goods->price);
    printf("商品库存: %d\n", goods->stock);
    printf("商品分类: %s\n", goods->category);
    printf("是否特价: %s\n", goods->is_special ? "是" : "否");
    printf("==============================\n");
}

// 按ID查找商品
Goods* find_goods_by_id(char *id) {
    ListNode *found = find_node(goods_list, id, compare_goods_by_id);
    return found ? (Goods*)found->data : NULL;
}

// 按名称查找商品
Goods* find_goods_by_name(char *name) {
    ListNode *found = find_node(goods_list, name, compare_goods_by_name);
    return found ? (Goods*)found->data : NULL;
}

// 更新库存
int update_goods_stock(char *id, int new_stock) {
    Goods *goods = find_goods_by_id(id);
    if (goods == NULL) {
        printf("商品不存在！\n");
        return -1;
    }
    
    goods->stock = new_stock;
    save_all_goods();
    printf("库存更新成功！\n");
    return 0;
}

// 删除商品
int delete_goods(char *id) {
    Goods *goods = find_goods_by_id(id);
    if (goods == NULL) {
        printf("商品不存在！\n");
        return -1;
    }
    
    delete_node(&goods_list, id, compare_goods_by_id);
    free(goods);
    save_all_goods();
    printf("商品删除成功！\n");
    return 0;
}

// 显示所有商品
void show_all_goods() {
    if (goods_list == NULL) {
        printf("暂无商品信息！\n");
        return;
    }
    
    printf("\n========== 所有商品 ==========\n");
    printf("%-10s %-20s %-10s %-10s %-15s %-10s\n", 
           "商品ID", "商品名称", "价格", "库存", "分类", "特价");
    printf("--------------------------------------------------------------------\n");
    
    ListNode *current = goods_list;
    while (current != NULL) {
        Goods *goods = (Goods*)current->data;
        printf("%-10s %-20s %-10.2f %-10d %-15s %-10s\n",
               goods->id,
               goods->name,
               goods->price,
               goods->stock,
               goods->category,
               goods->is_special ? "是" : "否");
        current = current->next;
    }
    printf("====================================================================\n");
}

// 显示特价商品
void show_special_goods() {
    printf("\n========== 特价商品 ==========\n");
    printf("%-10s %-20s %-10s %-10s %-15s\n", 
           "商品ID", "商品名称", "价格", "库存", "分类");
    printf("----------------------------------------------------------------\n");
    
    int count = 0;
    ListNode *current = goods_list;
    while (current != NULL) {
        Goods *goods = (Goods*)current->data;
        if (goods->is_special) {
            printf("%-10s %-20s %-10.2f %-10d %-15s\n",
                   goods->id,
                   goods->name,
                   goods->price,
                   goods->stock,
                   goods->category);
            count++;
        }
        current = current->next;
    }
    
    if (count == 0) {
        printf("暂无特价商品！\n");
    }
    printf("================================================================\n");
}

// 按分类显示商品
void show_goods_by_category(char *category) {
    printf("\n========== %s分类商品 ==========\n", category);
    printf("%-10s %-20s %-10s %-10s %-10s\n", 
           "商品ID", "商品名称", "价格", "库存", "特价");
    printf("----------------------------------------------------------------\n");
    
    int count = 0;
    ListNode *current = goods_list;
    while (current != NULL) {
        Goods *goods = (Goods*)current->data;
        if (strcmp(goods->category, category) == 0) {
            printf("%-10s %-20s %-10.2f %-10d %-10s\n",
                   goods->id,
                   goods->name,
                   goods->price,
                   goods->stock,
                   goods->is_special ? "是" : "否");
            count++;
        }
        current = current->next;
    }
    
    if (count == 0) {
        printf("暂无%s分类的商品！\n", category);
    }
    printf("================================================================\n");
}

// 商品初始化函数
void init_goods_system() {
    load_all_goods();
}